package net.csdn.business.gateway.utils;

import com.alibaba.fastjson2.JSONObject;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;

/**
 * @Auther: zhangyalei
 * @Date: 2022/9/28 09:38
 * @Description:
 */
public class ResponseUtils {

    /**
     * 设置webflux模型响应
     *
     * @param response ServerHttpResponse
     * @param status http状态码
     * @param error 响应错误码
     * @param description 响应错误描述
     * @return Mono<Void>
     */
    public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, HttpStatus status, String error, String description)
    {
        return webFluxResponseWriter(response, MediaType.APPLICATION_JSON_VALUE, status, error, description);
    }

    /**
     * 设置webflux模型响应
     *
     * @param response ServerHttpResponse
     * @param contentType content-type
     * @param status http状态码
     * @param error 响应错误码
     * @param description 响应错误描述
     * @return Mono<Void>
     */
    public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, String contentType, HttpStatus status, String error, String description)
    {
        response.setStatusCode(status);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, contentType);
        JSONObject params = new JSONObject();
        params.put("error", error);
        params.put("error_description", description);
        DataBuffer dataBuffer = response.bufferFactory().wrap(params.toJSONString().getBytes());
        return response.writeWith(Mono.just(dataBuffer));
    }
}
